package com.wwwarehouse.usercenter.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SmsReceiver extends BroadcastReceiver {

    public interface OnMessageReceivedListener {
        void onReceived(String code);
    }

    private OnMessageReceivedListener mOnMessageReceivedListener;

    public void setOnMessageReceivedListener(OnMessageReceivedListener onMessageReceivedListener) {
        this.mOnMessageReceivedListener = onMessageReceivedListener;
    }
  
    @Override  
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();

        if (bundle != null) {
            Object[] smsObj = (Object[]) bundle.get("pdus");

            for (Object object : smsObj) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) object);
                String body = smsMessage.getMessageBody();

                //利用正则提取验证码
                Pattern pattern = Pattern.compile("(\\d{6})"); //提取六位数字
                Matcher matcher = pattern.matcher(body); //进行匹配

                if(matcher.find()){ //匹配成功
                    String code = matcher.group(0);

                    if (mOnMessageReceivedListener != null) {
                        mOnMessageReceivedListener.onReceived(code);
                    }
                }
            }
        }  
    }
}  